# -*- coding: utf-8 -*-
import numpy as np
import os
import wrf_output
import gauge


def Decumulation(seq):
    result = [seq[i + 1] - seq[i] for i in range(len(seq) - 1)]
    result.insert(0, seq[0])
    return result


def main(path, domain, startTime, endTime):
    # domains = ['01', '02']
    # get every mp_cu group wrf_output and extract the center value
    mp = ['2', '6', '7']
    cu = ['0', '1', '2', '10']
    split_path = path.split('/')
    gridSpacing = split_path[-2]
    gauge_loc = ''
    if gridSpacing == '139':
        gauge_loc = r'F:/Research/Data/Gauge/Gauge_row_col_1.csv'
    elif gridSpacing == '51545':
        gauge_loc = r'F:/Research/Data/Gauge/Gauge_row_col_5.csv'
    elif gridSpacing == '103090':
        gauge_loc = r'F:/Research/Data/Gauge/Gauge_row_col_10.csv'
    results = []
    for i in mp:
        for j in cu:
            mp_cu = i + j
            if os.path.exists(path + mp_cu + '/'):
                input = path + mp_cu + '/wrfout_d' + domain + '_' + startTime
                all_gauges = wrf_output.GetAll(input, gauge_loc)
                all_gauges = Decumulation(all_gauges)
                results.append(all_gauges)
    results = np.asarray(results)
    min = np.min(results, axis=0)
    max = np.max(results, axis=0)
    band = np.array([min, max])
    band_50 = np.mean(band, axis=0)
    band_50 = band_50.astype(np.float64)
    # get the center gauge value
    gauge50 = gauge.Get50Gauge(startTime, endTime)

    # calculate dispersion statistic
    band_95 = np.sum(band, axis=0) * 0.95
    band_95 = band_95.astype(np.float64)
    band_5 = np.sum(band, axis=0) * 0.05
    band_5 = band_5.astype(np.float64)
    # dispersion statistic
    dispersion_d = np.mean((band_95 - band_5), axis=0)
    # normalized dispersion statistic
    # denominator = band_50.copy()
    # denominator[denominator == 0] = np.nan
    # nd = (band_95 - band_5) / denominator
    # masked_nd = np.ma.masked_array(nd, np.isnan(nd))
    # dispersion_nd = np.mean(masked_nd, axis=0).filled(np.nan)
    # print result
    # print("Dispersion statistic:\n", dispersion_d)
    # print("Normalized dispersion statistic:\n", dispersion_nd)

    # calculate MAE and MSE
    mae = np.abs(np.mean((band_50 - gauge50.values), axis=0))
    mse = np.mean(np.power((band_50 - gauge50.values), 2), axis=0)
    # print("MAE:\n", mae)
    # print("MSE:\n", mse)
    # output statistic result
    all_statistic = np.array([dispersion_d, mae, mse])
    all_statistic = all_statistic.T
    output_path = r'F:/Experiment/Research/Result/' + \
        split_path[3] + '/' + split_path[4] + '/' + \
        split_path[5] + '/' + split_path[6] + '/'
    if not os.path.exists(output_path):
        os.makedirs(output_path)
    np.savetxt(output_path + split_path[6] + '.csv', all_statistic,
               delimiter=',', fmt='%.2f', header='Dispersion,MAE,MSE')


if __name__ == "__main__":
    # new run
    path = r'F:/Research/WRF_Output/2008/01/1912/103090/'
    domain = r'03'
    startTime = r'2008-01-19_12_00_00'
    endTime = r'2008-01-22_00_00_00'
    main(path, domain, startTime, endTime)
    # path = r'F:/Research/WRF_Output/2008/03/1500/103090/'
    # domain = r'03'
    # startTime = r'2008-03-15_00_00_00'
    # endTime = r'2008-03-16_12_00_00'
    # main(path, domain, startTime, endTime)
    # path = r'F:/Research/WRF_Output/2008/09/2900/139/'
    # domain = r'03'
    # startTime = r'2008-09-29_00_00_00'
    # endTime = r'2008-10-02_06_00_00'
    # main(path, domain, startTime, endTime)
    # path = r'F:/Research/WRF_Output/2008/12/1200/103090/'
    # domain = r'03'
    # startTime = r'2008-12-12_00_00_00'
    # endTime = r'2008-12-14_06_00_00'
    # main(path, domain, startTime, endTime)
